package com.htc.callcare.asyntask;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import com.htc.callcare.database.Database;
import com.htc.callcare.infrastructure.globalVar;
import com.htc.callcare.model.VoiceMailModel;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class AsynLoadAllVoiceMailFile extends
		AsyncTask<String, Integer, ArrayList<VoiceMailModel>> {

	Context context;
	ProgressDialog progressDialog;
	String progressMessage;
	Database database;

	public AsynLoadAllVoiceMailFile(Context context, String progressMessage) {
		super();
		this.context = context;
		this.progressMessage = progressMessage;
		database = new Database(context);
	}

	@Override
	protected void onPreExecute() {

		progressDialog = ProgressDialog
				.show(context, "", progressMessage, true);
	}

	@Override
	protected void onPostExecute(ArrayList<VoiceMailModel> result) {
		// TODO Auto-generated method stub
		progressDialog.dismiss();
	}

	@Override
	protected ArrayList<VoiceMailModel> doInBackground(String... params) {
		ArrayList<VoiceMailModel> list = new ArrayList<VoiceMailModel>();
		File root = new File(globalVar.voiceMailDir);
		{
			try {
				if (root.listFiles().length > 0) {
					for (File file : root.listFiles()) {
						if (file.getName().endsWith(globalVar.amrType)) {
							VoiceMailModel model = new VoiceMailModel(
									file.getName());
							list.add(model);
							//If not exist in database, it will be added
							database.addVoiceMailNew(model.getFileUri());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (list.size() > 0) {
			return sortList(newList(list));
		} else {
			return list;
		}
	}

	// add separator
	public ArrayList<VoiceMailModel> newList(ArrayList<VoiceMailModel> voiceMails) {
		voiceMails.add(0, new VoiceMailModel(voiceMails.get(0).getCallDay(), 1));
		for (int i = 0; i < voiceMails.size(); i++) {
			if (i + 1 < voiceMails.size()) {
				// Add separator
				if (!voiceMails.get(i).getCallDay()
						.equals(voiceMails.get(i + 1).getCallDay())) {
					voiceMails.add(i + 1,
							new VoiceMailModel(voiceMails.get(i + 1)
									.getCallDay(), 1));
				}
			}
		}
		return voiceMails;
	}

	// Sort List
	public ArrayList<VoiceMailModel> sortList(
			ArrayList<VoiceMailModel> voiceMails) {
		Collections.sort(voiceMails);
		return voiceMails;
	}
}
